package com.elinkway.infinitemovies.download;

import android.R.integer;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;

import com.elinkway.infinitemovies.bean.LocalVideoEpisode;
import com.elinkway.infinitemovies.bean.PlayData;
import com.elinkway.infinitemovies.bean.PlayRecord;
import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.dao.DownLoadPlayRecordDao;
import com.elinkway.infinitemovies.dao.PlayRecordDao;
import com.elinkway.infinitemovies.service.DownloadService;
import com.elinkway.infinitemovies.ui.activity.play.PlayActivitySelfOwn;
import com.elinkway.infinitemovies.ui.activity.play.PlayerUtils;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.NetWorkTypeUtils;
import com.elinkway.infinitemovies.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class DownloadManager {
    private Context mContext;
    private DownloadProvider mProvider;
    private ArrayList<DownloadObserver> mObservers;
    public int DOWNLOADING_NUM = 0;
    public ArrayList<DownloadEntity> entitys;
    private final String FROM = "download";

    // private PlayHistoryDao mPlayHistoryDao;

    public DownloadManager(Context context) {
        this.mContext = context;
        mObservers = new ArrayList<DownloadObserver>();
        this.mProvider = new DownloadProvider(this);
    }

    public DownloadManager() {

    }

    public void download(DownloadEntity entity) {
        entity.setDisplayName(DownloadHelper.constructName(entity));
        Intent intent = new Intent(mContext, DownloadService.class);
        intent.setAction(DownloadService.ACTION_ADD_TO_DOWNLOAD);
        intent.putExtra(DownloadService.EXTRA_MEDIAITEM_ENTRY, entity);
        mContext.startService(intent);
    }

    public void download() {
        if (entitys == null)
            return;
        for (DownloadEntity entity : entitys) {
            download(entity);
        }
        entitys = null;
    }

    public void add(DownloadEntity entity) {
        if (entitys == null) {
            entitys = new ArrayList<DownloadEntity>();
        }
        entity.setDisplayName(DownloadHelper.constructName(entity));
        entitys.add(entity);
    }

    public boolean cancelAdd(DownloadEntity entity) {
        boolean hasRemoved = false;
        if (null != entity && null != entitys && entitys.size() > 0) {
            DownloadEntity addedEntity = null;
            for (int i = 0; i < entitys.size(); i++) {
                addedEntity = entitys.get(i);
                if (entity.getId().equals(addedEntity.getId())) {
                    entitys.remove(i);
                    hasRemoved = true;
                    break;
                }
            }
        }
        return hasRemoved;
    }

    public void cancel(DownloadEntity entity) {
        entitys = null;

    }

    public void download(ArrayList<DownloadJob> jobs, SparseArray<DownloadFolderJob> floderJobs) {

    }

    public DownloadProvider getProvider() {
        return mProvider;
    }

    public ArrayList<DownloadJob> getAllDownloads() {
        return mProvider.getAllDownloads();
    }

    public ArrayList<DownloadJob> getCompletedDownloads() {
        return mProvider.getCompletedDownloads();
    }

    public int getRemainNum() {
        return mProvider.getRemainNum();
    }


    public ArrayList<DownloadJob> getQueuedDownloads() {
        return mProvider.getQueuedDownloads();
    }

    public SparseArray<DownloadFolderJob> getDownloadFolderJobs() {
        return mProvider.getFolderJobs();
    }

    public synchronized void deregisterDownloadObserver(DownloadObserver observer) {
        mObservers.remove(observer);
    }

    public synchronized void registerDownloadObserver(DownloadObserver observer) {
        mObservers.add(observer);
    }

    public synchronized void notifyObservers() {
        for (DownloadObserver observer : mObservers) {
            observer.onDownloadChanged(this);
        }
    }

    public synchronized void notifyDownloadEnd(DownloadJob job) {
        MoviesConstant.isRefreshMyFragment = true;
        for (DownloadObserver observer : mObservers) {
            observer.onDownloadEnd(this);
        }
    }

    public void deleteDownload(DownloadJob job) {
        MoviesConstant.isRefreshMyFragment = true;
        mProvider.removeDownload(job);
        job.notifyDownloadOnPause();
        DownloadEntity entity = job.getEntity();
        // add by xj:删除物理文件
        if (entity.getMid() != null) {
            deleteHistoryDb(job.getEntity().getMid(), job.getEntity().getId(), job);

        }
    }

    private void deleteHistoryDb(final String mid, final String hashid, final DownloadJob job) {
        new Thread() {
            public void run() {
                removeDownloadFromDisk(job);
                // if (mPlayHistoryDao == null) {
                // mPlayHistoryDao = PlayHistoryDao.getInstance(mContext);
                // }
                // PlayHistoryInfo playHistoryInfo = mPlayHistoryDao.queryByHashid(mid);
                // if (playHistoryInfo != null) {
                // LogUtils.e("SWS", "deleteHistoryDb - historyId == " + playHistoryInfo.getHashid()
                // + " , " + hashid);
                // String purl = playHistoryInfo.getPurl();
                // if (purl != null && !purl.equals("") && !purl.contains("jobsfe.funshion.com")
                // && !purl.contains("p.funshion.com")) {
                // mPlayHistoryDao.deleteHashId(hashid);
                // }
                // }
            }

            ;
        }.start();
    }

    private void removeDownloadFromDisk(DownloadJob job) {
        DownloadEntity Entity = job.getEntity();
        String downloadPath = null;
        String path = null;
        if (null != Entity) {
            downloadPath = Entity.getPath();
        }
        if (!TextUtils.isEmpty(downloadPath)) {
            path = DownloadHelper.getPath(Entity, downloadPath);
        } else {
            path = DownloadHelper.getPath(Entity, DownloadHelper.getDownloadPath());
        }
        try {
            File file = new File(path);
            if (file.exists()) {
                delete(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 递归，删除m3u8文件
     */
    public void delete(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }
        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                file.delete();
                return;
            }
            for (int i = 0; i < childFiles.length; i++) {
                delete(childFiles[i]);
            }
            file.delete();
        }
    }

    /**
     * 下载m3u8/mp4之前，删除0字节的mp4/m3u8文件。
     * 因为在mp4下载时，会先创建空的mp4文件，但是mp4无法下载，切换到m3u8下载，这样，就冗余了一个空的mp4文件，需要删除.
     */
    public void deleteEmptyFile(String path) {
        File file = new File(path);
        if (null != file && file.isFile() && file.length() == 0) {
            file.delete();
        } else if (null != file && file.isDirectory()) {
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length <= 1) {
                delete(file);
            }
        }
    }

    // start next task
    public synchronized void startNextTask() {
        ArrayList<DownloadJob> queuedDownloads = mProvider.getQueuedDownloads();

        synchronized (queuedDownloads) {
            int num = getMaxDownloadNum();
            if (DOWNLOADING_NUM < num) {
                for (DownloadJob job : queuedDownloads) {
                    if ((job.getStatus() == DownloadJob.WAITING || job.getStatus() == DownloadJob.NO_USER_PAUSE)
                            && job.getExceptionType() != DownloadJob.NO_SD
                            && job.getExceptionType() != DownloadJob.FILE_NOT_FOUND) {
                        job.start();
                    }

                    if (DOWNLOADING_NUM >= num)
                        break;
                }
            }
        }
    }

    public void setStatus(DownloadEntity entity, int status) {
        mProvider.setStatus(entity, status);
    }

    public void setIfWatch(DownloadEntity entity, String ifWatch) {
        mProvider.setIfWatch(entity, ifWatch);
    }

    public boolean selectDownloadJobByMid(String mid) {
        return mProvider.selectDownloadJobByMid(mid);
    }

    public int getMaxDownloadNum() {
        SharedPreferences bgDownloadSharePreference =
                mContext.getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE,
                        Context.MODE_PRIVATE);
        String download_num =
                bgDownloadSharePreference.getString(SettingManage.DOWNLOAD_NUM_SAME_TIME, "1");
        return Integer.parseInt(download_num);
    }

    public boolean IsDownloadcan3g() {
        SharedPreferences bgDownloadSharePreference =
                mContext.getSharedPreferences(SettingManage.SETTING_RELATIVE_SHAREPREFERENCE,
                        Context.MODE_PRIVATE);
        Boolean IsDownloadcan3g =
                bgDownloadSharePreference.getBoolean(SettingManage.IS_DOWNLOAD_CAN_3G, false);
        return IsDownloadcan3g;
    }

    public void playVideo(DownloadJob job) {
        ArrayList<String> path = new ArrayList<>();
        DownloadEntity eDownloadEntity = job.getEntity();
        if (DownloadInfo.M3U8.equals(eDownloadEntity.getDownloadType())) {
            path.add(DownloadHelper.getAbsolutePath(eDownloadEntity, eDownloadEntity.getPath()) + "/" + eDownloadEntity.getSaveName() + ".m3u8");
        } else {
            File file = new File(DownloadHelper.getPath(job.getEntity(), job.getEntity().getPath()));
            if (file.exists() && !file.isDirectory()) {
                path.add("file://" + DownloadHelper.getPath(job.getEntity(), job.getEntity().getPath()));
            } else if(file.exists() && file.isDirectory()){
                int mp4PieceLen = file.listFiles().length;
                for (int m = 0; m < mp4PieceLen; m++) {
                    path.add("file://" + eDownloadEntity.getPath() + "/" + eDownloadEntity.getSaveName() + "/" + m +".mp4");
                }
            }
        }
        DownloadEntity entity = job.getEntity();
        // 创建播放本地视频的类对象
        LocalVideoEpisode localVideoEpisode = new LocalVideoEpisode();
        localVideoEpisode.setAid(entity.getMid());
        localVideoEpisode.setDownType(entity.getDownloadType());
        localVideoEpisode.setPorder(entity.getPorder());
        localVideoEpisode.setName(entity.getMedianame());
        localVideoEpisode.setPlay_url(path);
        localVideoEpisode.setId(entity.getId());
        localVideoEpisode.setVt(entity.getVt());
        // 本地大数据上报需要字段
        localVideoEpisode.setSite(entity.getSite());
        localVideoEpisode.setMid(entity.getMid());
        localVideoEpisode.setLVideoMid(entity.getLVideoMid());
        localVideoEpisode.setCloudId(entity.getCloudId());
        localVideoEpisode.setGlobaVid(entity.getGlobaVid());

        ArrayList<LocalVideoEpisode> localVideoEpisodeList = new ArrayList<LocalVideoEpisode>(1);
        localVideoEpisodeList.add(localVideoEpisode);
        PlayData mPlayData = new PlayData();
        // 设置播放的是本地的文件
        mPlayData.setIsLocalVideo(true);
        mPlayData.setmLocalDataLists(localVideoEpisodeList);
        mPlayData.setPorder(entity.getPorder());// 知道播的是哪一集播放器
        mPlayData.setAid(entity.getMid());
        mPlayData.setCategory(entity.getCategory());
        mPlayData.setFrom(FROM);
        mPlayData.setmViewName(entity.getMedianame());
        new PlayVideoTask().execute(mContext, mPlayData);
    }

    public void playVideoList(List<DownloadJob> jobs, DownloadJob job, String title) {
        ArrayList<LocalVideoEpisode> localVideoEpisodeList =
                new ArrayList<LocalVideoEpisode>(jobs.size());
        // 创建播放本地视频的类对象
        for (int i = 0; i < jobs.size(); i++) {
            ArrayList<String> path = new ArrayList<>();
            DownloadEntity eDownloadEntity = jobs.get(i).getEntity();

            if (DownloadInfo.M3U8.equals(eDownloadEntity.getDownloadType())) {
                path.add(DownloadHelper.getAbsolutePath(eDownloadEntity, eDownloadEntity.getPath()) + "/" + eDownloadEntity.getSaveName() + ".m3u8");
            } else {
                File file = new File(DownloadHelper.getPath(eDownloadEntity, eDownloadEntity.getPath()));
                if (file.exists() && !file.isDirectory()) {
                    path.add("file://" + DownloadHelper.getPath(eDownloadEntity, eDownloadEntity.getPath()));
                } else if(file.exists() && file.isDirectory()){
                    int mp4PieceLen = file.listFiles().length;
                    for (int m = 0; m < mp4PieceLen; m++) {
                        path.add("file://" + eDownloadEntity.getPath() + "/" + eDownloadEntity.getSaveName() + "/" + m +".mp4");
                    }
                }
            }

            LogUtils.e("zhaopei", "playVideoList " + path);
            LocalVideoEpisode localVideoEpisode = new LocalVideoEpisode();
            localVideoEpisode.setAid(eDownloadEntity.getMid());
            localVideoEpisode.setPorder(eDownloadEntity.getPorder());
            localVideoEpisode.setName(eDownloadEntity.getMedianame());
            localVideoEpisode.setPlay_url(path);
            localVideoEpisode.setSite(eDownloadEntity.getSite());
            localVideoEpisode.setId(eDownloadEntity.getId());
            localVideoEpisode.setVt(eDownloadEntity.getVt());
            localVideoEpisode.setDownType(eDownloadEntity.getDownloadType());
            localVideoEpisodeList.add(localVideoEpisode);

        }

        DownloadEntity entity = job.getEntity();
        PlayData mPlayData = new PlayData();
        // 设置播放的是本地的文件
        mPlayData.setIsLocalVideo(true);
        mPlayData.setmLocalDataLists(localVideoEpisodeList);
        mPlayData.setPorder(entity.getPorder());// 知道播的是哪一集播放器
        mPlayData.setAid(entity.getMid());
        mPlayData.setCategory(entity.getCategory());
        mPlayData.setFrom(FROM);
        mPlayData.setmViewName(title);

        new PlayVideoTask().execute(mContext, mPlayData);
    }

    public class PlayVideoTask extends AsyncTask<Object, integer, Object> {
        private Context context;
        private PlayData playData;
        // private PlayHistoryInfo historyInfo;
        private boolean isSendLocalHistory;

        @Override
        protected Object doInBackground(Object... params) {
            if (null != params[0] && params[0] instanceof Context) {
                context = (Context) params[0];
            }
            if (null != params[1] && params[1] instanceof PlayData) {
                playData = (PlayData) params[1];
            }

            PlayRecord playRecord = null;
            String aid = playData.getAid();

            if (!TextUtils.isEmpty(aid)) {
                if (playData.getIsLocalVideo()) {
                    DownLoadPlayRecordDao downloadPlayRecord =
                            DownLoadPlayRecordDao.getInstance(context);
                    playRecord = downloadPlayRecord.getByAidAndPorder(aid, playData.getPorder());
                } else {
                    PlayRecordDao playRecordDao = new PlayRecordDao(context);
                    playRecord = playRecordDao.getByAid(aid);
                }
            }

            if (null == playRecord) {
                playRecord = new PlayRecord();
            }
            playData.setmPlayRecord(playRecord);
            return null;
        }

        @Override
        protected void onPostExecute(Object result) {
            if (isXIAOMI()) {
                LocalVideoEpisode localVideoEpisode = getCurrLocalEisode(playData);
                if (PlayerUtils.DOWNLOAD_M3U8.equalsIgnoreCase(localVideoEpisode.getDownType())) {
                    jumpToSystemPlayer(context, localVideoEpisode);
                } else {
                    jumpToSelfPlayer(context, playData);
                }
            } else {
                jumpToSelfPlayer(context, playData);
            }
        }
    }

    private void jumpToSelfPlayer(Context context, PlayData playData) {
        Intent intent = new Intent(context, PlayActivitySelfOwn.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(Utils.PLAY_DATA, playData);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


    /**
     * 当前播放的视频
     *
     */
    private LocalVideoEpisode getCurrLocalEisode(PlayData playData) {
        ArrayList<LocalVideoEpisode> localDataLists = playData.getmLocalDataLists();
        String porder = playData.getPorder();
        if (!TextUtils.isEmpty(porder) && null != localDataLists && localDataLists.size() > 0) {
            int playSize = localDataLists.size();
            boolean isFindEpisode = false;
            // 查找当前影片位置
            for (int i = 0; i < playSize; i++) {
                LocalVideoEpisode localVideoEpisode = localDataLists.get(i);
                if (null != localVideoEpisode) {
                    if (porder.equals(localVideoEpisode.getPorder())) {
                        isFindEpisode = true;
                        return localVideoEpisode;
                    }
                }
            }
            // 如果没找到则取第一个
            if (!isFindEpisode) {
                return localDataLists.get(0);
            }
        }
        return null;
    }


    public void jumpToSystemPlayer(Context context, LocalVideoEpisode localVideoEpisode) {
        String playUrl = "file://" + localVideoEpisode.getPlay_url();
        if (!TextUtils.isEmpty(playUrl)) {
            playUrl.replace(" ", "%20");
            Uri uri = Uri.parse(playUrl);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(uri, "video/mp4");
            // Activity activity = MoviesApplication.getInstance().getActivity();
            // if (null != activity) {
            context.startActivity(intent);
            // }
        }
    }

    public boolean isXIAOMI() {
        String deviceMode = Utils.getDeviceMode();
        String deviceVersion = Utils.getDeviceVersion();
        return ((deviceMode.contains(PlayerUtils.MI) || deviceMode.contains(PlayerUtils.XIAOMI))
                && deviceVersion.contains(PlayerUtils.XIAOMI_LOCAL_VERSION) && !NetWorkTypeUtils
                .isNetAvailable());
    }

}
